import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../services/auth_service.dart';
import '../services/order_service.dart';
import '../models/order.dart';

class AdminOrdersScreen extends StatefulWidget {
  const AdminOrdersScreen({super.key});

  @override
  State<AdminOrdersScreen> createState() => _AdminOrdersScreenState();
}

class _AdminOrdersScreenState extends State<AdminOrdersScreen> {
  bool _isLoading = false;
  List<Order> _orders = [];
  String _selectedStatus = 'all';

  @override
  void initState() {
    super.initState();
    _loadOrders();
  }

  Future<void> _loadOrders() async {
    setState(() => _isLoading = true);
    try {
      final orders = await context.read<OrderService>().getOrders();
      setState(() {
        _orders = orders;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载订单失败: $e')),
      );
    }
  }

  Future<void> _updateOrderStatus(String orderId, OrderStatus status) async {
    setState(() => _isLoading = true);
    try {
      final success = await context.read<OrderService>().updateOrderStatus(
        orderId: orderId,
        status: status,
      );
      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('订单状态更新成功')),
        );
        _loadOrders();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('订单状态更新失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('错误: $e')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Color _getStatusColor(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return Colors.orange;
      case OrderStatus.processing:
        return Colors.blue;
      case OrderStatus.shipped:
        return Colors.purple;
      case OrderStatus.delivered:
        return Colors.green;
      case OrderStatus.cancelled:
        return Colors.red;
    }
  }

  String _getStatusText(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return '待处理';
      case OrderStatus.processing:
        return '处理中';
      case OrderStatus.shipped:
        return '已发货';
      case OrderStatus.delivered:
        return '已送达';
      case OrderStatus.cancelled:
        return '已取消';
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = context.watch<AuthService>().user;
    
    // 检查是否是管理员
    if (user?.email != '123455') {
      return Scaffold(
        appBar: AppBar(title: const Text('访问被拒绝')),
        body: const Center(
          child: Text('只有管理员可以访问此页面'),
        ),
      );
    }

    final filteredOrders = _selectedStatus == 'all'
        ? _orders
        : _orders.where((order) => order.status.toString() == _selectedStatus).toList();

    return Scaffold(
      appBar: AppBar(
        title: const Text('订单管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadOrders,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.all(16),
                  child: Row(
                    children: [
                      _buildStatusChip('all', '全部'),
                      const SizedBox(width: 8),
                      _buildStatusChip(OrderStatus.pending.toString(), '待处理'),
                      const SizedBox(width: 8),
                      _buildStatusChip(OrderStatus.processing.toString(), '处理中'),
                      const SizedBox(width: 8),
                      _buildStatusChip(OrderStatus.shipped.toString(), '已发货'),
                      const SizedBox(width: 8),
                      _buildStatusChip(OrderStatus.delivered.toString(), '已送达'),
                      const SizedBox(width: 8),
                      _buildStatusChip(OrderStatus.cancelled.toString(), '已取消'),
                    ],
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    padding: const EdgeInsets.all(16),
                    itemCount: filteredOrders.length,
                    itemBuilder: (context, index) {
                      final order = filteredOrders[index];
                      return Card(
                        child: ExpansionTile(
                          title: Text('订单号: ${order.id}'),
                          subtitle: Text(
                            '${DateFormat('yyyy-MM-dd HH:mm').format(order.orderDate)} - ${_getStatusText(order.status)}',
                          ),
                          leading: CircleAvatar(
                            backgroundColor: _getStatusColor(order.status),
                            child: Icon(
                              _getStatusIcon(order.status),
                              color: Colors.white,
                            ),
                          ),
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(16),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('用户: ${order.userId}'),
                                  const SizedBox(height: 8),
                                  Text('总金额: ¥${order.totalAmount}'),
                                  const SizedBox(height: 8),
                                  const Text('商品列表:'),
                                  ...order.items.map((item) => ListTile(
                                        leading: Image.network(
                                          item.product.imageUrl,
                                          width: 50,
                                          height: 50,
                                          fit: BoxFit.cover,
                                          errorBuilder: (context, error, stackTrace) =>
                                              const Icon(Icons.error),
                                        ),
                                        title: Text(item.product.name),
                                        subtitle: Text('数量: ${item.quantity}'),
                                        trailing: Text('¥${item.product.price}'),
                                      )),
                                  const SizedBox(height: 16),
                                  if (order.status != OrderStatus.delivered &&
                                      order.status != OrderStatus.cancelled)
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        TextButton(
                                          onPressed: () {
                                            final nextStatus = _getNextStatus(order.status);
                                            if (nextStatus != null) {
                                              _updateOrderStatus(order.id, nextStatus);
                                            }
                                          },
                                          child: Text(
                                            _getNextStatusText(order.status) ?? '',
                                          ),
                                        ),
                                      ],
                                    ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
    );
  }

  Widget _buildStatusChip(String status, String label) {
    final isSelected = _selectedStatus == status;
    return FilterChip(
      label: Text(label),
      selected: isSelected,
      onSelected: (selected) {
        setState(() => _selectedStatus = status);
      },
    );
  }

  IconData _getStatusIcon(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return Icons.pending;
      case OrderStatus.processing:
        return Icons.sync;
      case OrderStatus.shipped:
        return Icons.local_shipping;
      case OrderStatus.delivered:
        return Icons.check_circle;
      case OrderStatus.cancelled:
        return Icons.cancel;
    }
  }

  OrderStatus _getNextStatus(OrderStatus currentStatus) {
    switch (currentStatus) {
      case OrderStatus.pending:
        return OrderStatus.processing;
      case OrderStatus.processing:
        return OrderStatus.shipped;
      case OrderStatus.shipped:
        return OrderStatus.delivered;
      case OrderStatus.delivered:
      case OrderStatus.cancelled:
        return currentStatus;
    }
  }

  String? _getNextStatusText(OrderStatus currentStatus) {
    switch (currentStatus) {
      case OrderStatus.pending:
        return '开始处理';
      case OrderStatus.processing:
        return '标记发货';
      case OrderStatus.shipped:
        return '确认送达';
      case OrderStatus.delivered:
      case OrderStatus.cancelled:
        return null;
    }
  }
} 